package com.css.zfzx.sjcj.modules.hddcwyGeomorphySvySamplePoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.analysis.vo.HddcAppZztCountVo;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyReProf.repository.entity.HddcGeomorphysvyreprofEntity;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvySamplePoint.repository.HddcGeomorphysvysamplepointRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvySamplePoint.repository.entity.HddcGeomorphysvysamplepointEntity;
import com.css.zfzx.sjcj.modules.hddcwyFaultSvyPoint.repository.entity.HddcWyFaultsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvySamplePoint.repository.HddcWyGeomorphysvysamplepointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvySamplePoint.repository.HddcWyGeomorphysvysamplepointRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvySamplePoint.repository.entity.HddcWyGeomorphysvysamplepointEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvySamplePoint.service.HddcWyGeomorphysvysamplepointService;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvySamplePoint.viewobjects.HddcWyGeomorphysvysamplepointQueryParams;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvySamplePoint.viewobjects.HddcWyGeomorphysvysamplepointVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author lihelei
 * @date 2020-12-01
 */
@Service
public class HddcWyGeomorphysvysamplepointServiceImpl implements HddcWyGeomorphysvysamplepointService {

	@Autowired
    private HddcWyGeomorphysvysamplepointRepository hddcWyGeomorphysvysamplepointRepository;
    @Autowired
    private HddcWyGeomorphysvysamplepointNativeRepository hddcWyGeomorphysvysamplepointNativeRepository;
    @Autowired
    private HddcGeomorphysvysamplepointRepository hddcGeomorphysvysamplepointRepository;
    @Override
    public JSONObject queryHddcWyGeomorphysvysamplepoints(HddcWyGeomorphysvysamplepointQueryParams queryParams,int curPage,int pageSize) {
        Page<HddcWyGeomorphysvysamplepointEntity> hddcWyGeomorphysvysamplepointPage = this.hddcWyGeomorphysvysamplepointNativeRepository.queryHddcWyGeomorphysvysamplepoints(queryParams,curPage,pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcWyGeomorphysvysamplepointPage);
        return jsonObject;
    }


    @Override
    public HddcWyGeomorphysvysamplepointEntity getHddcWyGeomorphysvysamplepoint(String uuid) {
        HddcWyGeomorphysvysamplepointEntity hddcWyGeomorphysvysamplepoint = this.hddcWyGeomorphysvysamplepointRepository.findById(uuid).orElse(null);
         return hddcWyGeomorphysvysamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeomorphysvysamplepointEntity saveHddcWyGeomorphysvysamplepoint(HddcWyGeomorphysvysamplepointEntity hddcWyGeomorphysvysamplepoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcWyGeomorphysvysamplepoint.setUuid(uuid);
        if(StringUtils.isEmpty(hddcWyGeomorphysvysamplepoint.getCreateUser())){
            hddcWyGeomorphysvysamplepoint.setCreateUser(PlatformSessionUtils.getUserId());
        }
        hddcWyGeomorphysvysamplepoint.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcWyGeomorphysvysamplepoint.setIsValid("1");

        HddcGeomorphysvysamplepointEntity hddcGeomorphysvysamplepointEntity=new HddcGeomorphysvysamplepointEntity();
        BeanUtils.copyProperties(hddcWyGeomorphysvysamplepoint,hddcGeomorphysvysamplepointEntity);
        hddcGeomorphysvysamplepointEntity.setExtends4(hddcWyGeomorphysvysamplepoint.getTown());
        hddcGeomorphysvysamplepointEntity.setExtends5(String.valueOf(hddcWyGeomorphysvysamplepoint.getLon()));
        hddcGeomorphysvysamplepointEntity.setExtends6(String.valueOf(hddcWyGeomorphysvysamplepoint.getLat()));
        this.hddcGeomorphysvysamplepointRepository.save(hddcGeomorphysvysamplepointEntity);

        this.hddcWyGeomorphysvysamplepointRepository.save(hddcWyGeomorphysvysamplepoint);
        return hddcWyGeomorphysvysamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeomorphysvysamplepointEntity updateHddcWyGeomorphysvysamplepoint(HddcWyGeomorphysvysamplepointEntity hddcWyGeomorphysvysamplepoint) {
        HddcWyGeomorphysvysamplepointEntity entity = hddcWyGeomorphysvysamplepointRepository.findById(hddcWyGeomorphysvysamplepoint.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcWyGeomorphysvysamplepoint);
        hddcWyGeomorphysvysamplepoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWyGeomorphysvysamplepoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWyGeomorphysvysamplepointRepository.save(hddcWyGeomorphysvysamplepoint);
        return hddcWyGeomorphysvysamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWyGeomorphysvysamplepoints(List<String> ids) {
        List<HddcWyGeomorphysvysamplepointEntity> hddcWyGeomorphysvysamplepointList = this.hddcWyGeomorphysvysamplepointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcWyGeomorphysvysamplepointList) && hddcWyGeomorphysvysamplepointList.size() > 0) {
            for(HddcWyGeomorphysvysamplepointEntity hddcWyGeomorphysvysamplepoint : hddcWyGeomorphysvysamplepointList) {
                this.hddcWyGeomorphysvysamplepointRepository.delete(hddcWyGeomorphysvysamplepoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public BigInteger queryHddcWyGeomorphysvysamplepoint(HddcAppZztCountVo queryParams) {
        BigInteger bigInteger = hddcWyGeomorphysvysamplepointNativeRepository.queryHddcWyGeomorphysvysamplepoint(queryParams);
        return bigInteger;
    }

    @Override
    public List<HddcWyGeomorphysvysamplepointEntity> findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(String userId, String taskId, String projectId, String isValid) {
        List<HddcWyGeomorphysvysamplepointEntity> list = hddcWyGeomorphysvysamplepointRepository.findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(userId, taskId, projectId, isValid);
        return list;
    }

    @Override
    public void exportFile(HddcAppZztCountVo queryParams, HttpServletResponse response) {
        List<HddcWyGeomorphysvysamplepointEntity> hddcWyGeomorphysvysamplepointEntity = hddcWyGeomorphysvysamplepointNativeRepository.exportSamplePoint(queryParams);
        List<HddcWyGeomorphysvysamplepointVO> list=new ArrayList<>();
        for (HddcWyGeomorphysvysamplepointEntity entity:hddcWyGeomorphysvysamplepointEntity) {
            HddcWyGeomorphysvysamplepointVO hddcWyGeomorphysvysamplepointVO=new HddcWyGeomorphysvysamplepointVO();
            BeanUtils.copyProperties(entity,hddcWyGeomorphysvysamplepointVO);
            list.add(hddcWyGeomorphysvysamplepointVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"微地貌测量采样点-点","微地貌测量采样点-点", HddcWyGeomorphysvysamplepointVO.class,"微地貌测量采样点-点.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcWyGeomorphysvysamplepointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcWyGeomorphysvysamplepointVO.class, params);
            List<HddcWyGeomorphysvysamplepointVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcWyGeomorphysvysamplepointVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcWyGeomorphysvysamplepointVO hddcWyGeomorphysvysamplepointVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + hddcWyGeomorphysvysamplepointVO.getRowNum() + "行" + hddcWyGeomorphysvysamplepointVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcWyGeomorphysvysamplepointVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcWyGeomorphysvysamplepointEntity hddcWyGeomorphysvysamplepointEntity = new HddcWyGeomorphysvysamplepointEntity();
            HddcWyGeomorphysvysamplepointVO hddcWyGeomorphysvysamplepointVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcWyGeomorphysvysamplepointVO, hddcWyGeomorphysvysamplepointEntity);
            saveHddcWyGeomorphysvysamplepoint(hddcWyGeomorphysvysamplepointEntity);
        }
    }

    @Override
    public List<HddcWyGeomorphysvysamplepointEntity> findAllByCreateUserAndIsValid(String userId,String isValid) {
        List<HddcWyGeomorphysvysamplepointEntity> list = hddcWyGeomorphysvysamplepointRepository.findAllByCreateUserAndIsValid(userId,isValid);
        return list;
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcWyGeomorphysvysamplepointEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeomorphysvysamplepointRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyGeomorphysvysamplepointEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeomorphysvysamplepointRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcWyGeomorphysvysamplepointEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeomorphysvysamplepointRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyGeomorphysvysamplepointEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeomorphysvysamplepointRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }

    }










}
